import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'recordDetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'Util.dart';
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';

class RecordPage extends StatefulWidget {
  RecordPage({Key key, this.title, this.para}) : super(key: key);
  final String title;
  final Map<String, dynamic> para;
  @override
  _RecordPage createState() => _RecordPage();
}

class _RecordPage extends State<RecordPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }
  loadData(){
    SharedPreferences.getInstance().then((value){
      setState(() {
        String domain = value.getString("buildings").toMap()["subdomain"].toString();
        String block_key = value.getString("buildings").toMap()["block_key"].toString();
        print(domain);
        Map<String, dynamic> dic = {};
        dic["api_key"] = "xQITe6bZFUrmeJbkcKgkUzajUI6FGLA";
        dic["lang"] = "en";
        dic["block_key"] = block_key;
        print(dic);
        var dio = Dio();
        if (ShareHandle.instance.proxy.length > 0){
          (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
            client.findProxy = (uri) {
              return ShareHandle.instance.proxy;
            };
          };
        }
        dio.post("${domain}/api/visitor/pending_list",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          print(result.item1);
          if (result.item2){
            setState(() {
              _dataList = List<Map<String, dynamic>>.from(result.item1["container"] ?? []);
              this.dataList = [{"time":"到訪時間","name":"姓名","build":"到訪單位"}];
              this.dataList.addAll(_dataList.map((e) => {"time":e["visit_date"].toString(),"name":e["visitor_name"].toString(),"build":e["rooms"].toString()}));

              // var dic = widget.para;
              // Navigator.push( context, MaterialPageRoute(builder: (context) => RecordDetailPage(title: widget.title,para: dic,customer: result.item1["container"],)),);
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error.toString());
        });
      });
    });
  }
  List<Map<String, dynamic>> _dataList = [];
  List<Map<String, String>> dataList = [{"time":"到訪時間","name":"姓名","build":"到訪單位"}];
  @override
  Widget build(BuildContext context) {
    List<TableRow> cards = [];
    dataList.asMap().forEach((i, v) {
      cards.add(TableRow(children: <Widget>[
        TableCell(child: Padding(padding: EdgeInsets.all(10),child: Center(child: Text(v["time"],style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),),)),
        TableCell(child: Center(child: Text(v["name"],style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),)),
        TableCell(child: Center(child: Text(v["build"],style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),)),
        TableCell(child: Center(child: i > 0 ? FlatButton(child: Image.asset("assets/images/arrow_right_green.png",width: 20,),onPressed: (){
          print(this._dataList[i-1]);
          var dic = widget.para;
          Navigator.push( context, MaterialPageRoute(builder: (context) => RecordDetailPage(title: widget.title,para: dic,customer:this._dataList[i-1])),);
        },) : null,),)
      ],decoration: BoxDecoration(color: i == 0 ? Colors.black12 : Colors.white)));

    });
    return Scaffold(
      appBar: AppBar(
          title: Text(widget.title),
          actions: <Widget>[
            FlatButton(
              child: Text("登出",style: TextStyle(color: Colors.white),),
              onPressed: () {
                Navigator.of(context).popUntil((route) => route.settings.name == "MyHome2Page");
              },
            )
          ]
      ),
      body: Column(
        children: <Widget>[
          Table(children: cards, border: TableBorder.all(),defaultVerticalAlignment: TableCellVerticalAlignment.middle,)
        ],
      ),
    );
  }
}
